package com.guyuan.live_meeting.utils;

import com.google.gson.Gson;
import com.guyuan.live_meeting.bean.UmengPushRequest;
import com.guyuan.live_meeting.bean.UmengPushResponse;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.web.util.UriComponentsBuilder;

import java.io.*;
import java.net.URI;
import java.util.logging.Logger;

@Service
public class UmengHttpClient {

    private static final String URL = "http://msg.umeng.com/api/send";
    private static final String REQUEST_METHOD = "POST";
    private static final String APP_MASTER_SECRET = "wllkfyfissy3ewrmgnxaxnvfv5wciyt9";
    private static final String APP_KEY = "5eaa4254167edd595500014e";
    private static final String UMENG_ALIAS_TYPE = "user_name_plus_id";
    private static final String NOTIFY_ACTIVITY = "com.gy.smartmanagement.umeng.VendorNotifyActivity";
    private Logger logger = Logger.getLogger(UmengHttpClient.class.getName());
    private HttpClient mHttpClient = new DefaultHttpClient();

    public enum ExtraDataType {
        DEFAULT, INSTANT_MEETING, AUTO_APPOINT_MEETING, MANUAL_APPOINT_MEETING, REFUSE_MEETING, MEETING_ENDED, MEETING_EDITED, MEETING_CANCEL, AUTO_APPOINT_MEETING_TIME_UP, MANUAL_APPOINT_MEETING_UP;


        public int toInteger() {
            switch (this) {
                case INSTANT_MEETING://即时会议
                    return 1;
                case AUTO_APPOINT_MEETING://预约会议（自启动）
                    return 2;
                case MANUAL_APPOINT_MEETING://预约会议（手动启动）
                    return 3;
                case REFUSE_MEETING://拒绝参会
                    return 4;
                case MEETING_ENDED://会议结束
                    return 5;
                case MEETING_EDITED://预约会议被编辑
                    return 6;
                case MEETING_CANCEL://预约会议被取消
                    return 7;
                case AUTO_APPOINT_MEETING_TIME_UP://预约会议（自启动）到时
                    return 8;
                case MANUAL_APPOINT_MEETING_UP://预约会议（手动启动）到时
                    return 9;
                case DEFAULT:
                default:
                    return -1;
            }
        }
    }


    /**
     * 友盟推送+厂商推送。某些消息在APP关闭的情况也要显示到通知栏，这时就要用这个。
     * 参考 https://developer.umeng.com/docs/66632/detail/68343
     *
     * @param extraData 根据dateType传入相应的json字符串
     * @return
     */
    public UmengPushResponse umungPushPlusVendorPush(String receivers, ExtraDataType extraDataType, String extraData,
                                                     String notifyTicker, String notifyTitle, String notifyText) throws IOException {
        return executePush(receivers, extraDataType, extraData, notifyTicker, notifyTitle, notifyText, true);
    }

    /**
     * 仅友盟推送。某些消息只需要在APP打开时才显示，这时就要用这个。
     * 参考 https://developer.umeng.com/docs/66632/detail/68343
     *
     * @param extraData 根据dateType传入相应的json字符串
     * @return
     */
    public UmengPushResponse umengPushOnly(String receivers, ExtraDataType extraDataType, String extraData,
                                           String notifyTicker, String notifyTitle, String notifyText) throws IOException {
        return executePush(receivers, extraDataType, extraData, notifyTicker, notifyTitle, notifyText, false);
    }

    private UmengPushResponse executePush(String receivers, ExtraDataType extraDataType, String extraData,
                                          String notifyTicker, String notifyTitle, String notifyText,
                                          boolean isUseVendorPush) throws IOException {
        UmengPushRequest request = genPushRequest(receivers, extraDataType, extraData, notifyTicker, notifyTitle, notifyText, isUseVendorPush);
        URI uri = UriComponentsBuilder.fromUriString(URL + "?sign=" + getUmengSign(request))
                .build()
                .toUri();

        HttpPost post = new HttpPost(uri);
        post.setHeader("User-Agent", "Mozilla/5.0");
        StringEntity se = new StringEntity(new Gson().toJson(request), "UTF-8");
        post.setEntity(se);
        HttpResponse response = mHttpClient.execute(post);
        int statusCode = response.getStatusLine().getStatusCode();
        InputStream inputStream = response.getEntity().getContent();
        BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
        StringBuffer sb = new StringBuffer();
        String line = null;
        while ((line = br.readLine()) != null) {
            sb.append(line);
        }
        String content = sb.toString().trim();
        if (statusCode == 200) {
            logger.warning("response from umeng:" + content);
            return new Gson().fromJson(content, UmengPushResponse.class);
        } else {
            UmengPushResponse umengPushResponse = new UmengPushResponse();
            umengPushResponse.setRet("FAIL");
            UmengPushResponse.Data data = new UmengPushResponse.Data();
            data.setError_code(statusCode);
            data.setError_msg(content);
            return umengPushResponse;
        }
    }

    /**
     * @param receivers
     * @param extraData    根据dateType传入相应的json字符串
     * @param notifyTicker
     * @param notifyTitle
     * @param notifyText
     * @return
     */
    private UmengPushRequest genPushRequest(String receivers, ExtraDataType extraDataType, String extraData,
                                            String notifyTicker, String notifyTitle, String notifyText,
                                            boolean isUseVendorPush) {
        //这里不要修改
        UmengPushRequest request = new UmengPushRequest();
        request.setAppkey(APP_KEY);
        request.setTimestamp(System.currentTimeMillis());
        request.setType("customizedcast");
        request.setAlias_type(UMENG_ALIAS_TYPE);
        request.setAlias(receivers);
        request.setMipush(isUseVendorPush);
        request.setMi_activity(NOTIFY_ACTIVITY);

        UmengPushRequest.Payload payload = new UmengPushRequest.Payload();
        payload.setDisplay_type("notification");

        UmengPushRequest.Payload.Body body = new UmengPushRequest.Payload.Body();
        body.setTicker(notifyTicker);
        body.setTitle(notifyTitle);
        body.setText(notifyText);
        body.setAfter_open("go_activity");
        body.setActivity(NOTIFY_ACTIVITY);

        UmengPushRequest.Payload.Extra extra = new UmengPushRequest.Payload.Extra();
        extra.setDataType(extraDataType.toInteger());
        extra.setData(extraData);

        payload.setExtra(extra);
        payload.setBody(body);

        request.setPayload(payload);

        return request;
    }

    private String getUmengSign(UmengPushRequest request) {
        StringBuilder sb = new StringBuilder();
        String json = new Gson().toJson(request);
        String s = String.format("%s%s%s%s", REQUEST_METHOD, URL, json, APP_MASTER_SECRET);
        try {
            sb.append(DigestUtils.md5DigestAsHex(s.getBytes("utf8")));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return sb.toString();
    }
}
